var db = require('../model');
var utils = require('../utils');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');


module.exports = {
  refreshToken: function(req, res, next) {
    if (req.decoded) {
      //重新生成签名
      var newToken = jwt.sign({
        data: req.decoded.data
      },
      config.secret, {
        expiresIn: '7d'
      });
      res.json(utils.formatResult({jwt:newToken}));
    } else {
      next(new errs.UnauthorizedError('token exp is overdue'));
    }
  },
  login: function(req, res, next) {
    var body = req.body,
    accounts = body.accounts,
    pwd = body.pwd;
    if(!accounts || !pwd){
      return next('accounts and pwd is wrong');
    }
    var md5 = crypto.createHash('md5');
    md5.update(pwd);
    pwd = md5.digest('hex');
    db.user.findOne({
      accounts: accounts
    }).then((user) => {
      if (user && user.pwd == pwd) {
        var token = jwt.sign({
          data:{
            id:user.id,
            _id:user._id,
            nick:user.nick,
            emailnotallow:user.emailnotallow,
            firends:user.firends,
            block:user.block
          }
        },
        config.secret, {
          expiresIn: '7d'
        });
        res.json(utils.formatResult({jwt:token}));
      } else {
        return next('accounts and pwd is wrong');
      }
    },
    (err) => {
      next(err);
    });
  }
};

